package cn.tj.wenda.cloud.config;

import cn.tj.wenda.cloud.interceptor.SqlInterceptor;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import org.apache.ibatis.plugin.Interceptor;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
//加上这个注解，使得支持事务
@EnableTransactionManagement
public class MyBatisConfiguration implements TransactionManagementConfigurer {

    @Autowired
    DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //分页插件
        PageInterceptor pageHelper = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("helperDialect","mysql");
        properties.setProperty("reasonable","true");
        properties.setProperty("supportMethodsArguments","true");
        properties.setProperty("params","count=countSql");
        properties.setProperty("pageSizeZero","true");
        pageHelper.setProperties(properties);
        //添加插件
        //bean.setPlugins(new Interceptor[]{pageHelper,new SqlInterceptor()});
        bean.setPlugins(new Interceptor[]{pageHelper});

        try {
//            Resource[] resources = new PathMatchingResourcePatternResolver()
//                    .getResources("classpath:mybatis/*.xml");
//            bean.setMapperLocations(resources);

//            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//            bean.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));

            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }



}
